package cn.xhjava.crm.workbench.controller;

import cn.xhjava.crm.commons.ReturnObject;
import cn.xhjava.crm.commons.SysContants;
import cn.xhjava.crm.commons.util.DateUtils;
import cn.xhjava.crm.commons.util.ExceptionUtil;
import cn.xhjava.crm.commons.util.UUIDUtils;
import cn.xhjava.crm.settings.domain.DicValue;
import cn.xhjava.crm.settings.domain.User;
import cn.xhjava.crm.settings.service.DicValueService;
import cn.xhjava.crm.settings.service.UserService;
import cn.xhjava.crm.workbench.domain.*;
import cn.xhjava.crm.workbench.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Author:   XiaHu
 * Date:     2023/6/27
 * 联系人
 */
@Controller
public class ContactsController {
    private static final Logger log = LoggerFactory.getLogger(ContactsController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private DicValueService dicValueService;

    @Autowired
    private ContactsService contactsService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private TranService tranService;

    @Autowired
    private ContactsRemarkService contactsRemarkService;


    @RequestMapping("/workbench/contacts/index")
    public String index(HttpServletRequest request) {
        log.info("跳转到 contacts index");
        //调用service层方法，查询动态数据
        List<User> userList = null;
        List<DicValue> appellationList = null;
        List<DicValue> sourceList = null;
        try {
            userList = userService.queryAllUsers();
            appellationList = dicValueService.queryDicValueByTypeCode("appellation");
            sourceList = dicValueService.queryDicValueByTypeCode("source");
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        //把数据保存到request中
        request.setAttribute("userList", userList);
        request.setAttribute("appellationList", appellationList);
        request.setAttribute("sourceList", sourceList);
        //请求转发
        return "workbench/contacts/index";
    }

    @RequestMapping("/workbench/contacts/queryContactsForPage")
    public @ResponseBody
    Object selectForPage(String owner,
                         String name,
                         String customerName,
                         String source,
                         String phone,
                         int pageNo, int pageSize, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("owner", owner);
        map.put("name", name);
        map.put("customerName", customerName);
        map.put("source", source);
        map.put("mphone", phone);
        map.put("beginNo", (pageNo - 1) * pageSize);
        map.put("pageSize", pageSize);
        map.put("userId", user.getId());
        //调用service层方法，查询数据
        List<Contacts> contactsList = null;
        int totalRows = 0;
        try {
            contactsList = contactsService.selectForPage(map);
            totalRows = contactsService.selectCountForPage(map);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        //根据查询结果结果，生成响应信息
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("contactsList", contactsList);
        retMap.put("totalRows", totalRows);
        return retMap;
    }


    @RequestMapping("/workbench/contacts/add")
    public @ResponseBody
    Object add(Contacts contacts, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        contacts.setId(UUIDUtils.getUUID());
        contacts.setCreateTime(DateUtils.formateDateTime(new Date()));
        contacts.setCreateBy(user.getId());
        contacts.setOwner(user.getId());

        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，保存创建的线索
            int ret = contactsService.add(contacts);

            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("添加成功");
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }
        return returnObject;
    }

    @RequestMapping("/workbench/contacts/addByCustomerId")
    public @ResponseBody
    Object addByCustomerId(Contacts contacts, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        contacts.setId(UUIDUtils.getUUID());
        contacts.setCreateTime(DateUtils.formateDateTime(new Date()));
        contacts.setCreateBy(user.getId());
        contacts.setOwner(user.getId());

        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，保存创建的线索
            int ret = contactsService.addByCustomerId(contacts);

            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setRetData(contacts);
                returnObject.setMessage("添加成功");
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }
        return returnObject;
    }

    // 查询
    @RequestMapping("/workbench/contacts/queryContactsById")
    public @ResponseBody
    Object selectById(String id) {
        //调用service层方法，查询市场活动
        Contacts contacts = null;
        try {
            contacts = contactsService.selectById(id);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        return contacts;
    }


    // 修改
    @RequestMapping("/workbench/contact/update")
    public @ResponseBody
    Object update(Contacts contacts, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        contacts.setEditTime(DateUtils.formateDateTime(new Date()));
        contacts.setEditBy(user.getId());

        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，修改联系人
            int ret = contactsService.update(contacts);

            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }
        return returnObject;
    }

    // 删除
    @RequestMapping("/workbench/contacts/delete")
    public @ResponseBody
    Object delete(String[] id) {
        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，删除市场活动
            int ret = contactsService.delete(id);
            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }
        return returnObject;
    }


    @RequestMapping("/workbench/contacts/detail")
    public String detail(String id, HttpServletRequest request) {
        Contacts contacts = null;
        List<ContactsRemark> remarkList = null;
        List<Activity> activityList = null;
        List<User> userList = null;
        List<DicValue> appellationList = null;
        List<DicValue> sourceList = null;
        List<Tran> transactionList = null;
        List<DicValue> stageList = null;
        List<DicValue> transactionTypeList = null;
        try {
            contacts = contactsService.selectDetailById(id);
            remarkList = contactsRemarkService.selectContactsRemarkByContactsId(id);
            activityList = activityService.selectContactsActivityRelationByContactsId(id);
            userList = userService.queryAllUsers();
            appellationList = dicValueService.queryDicValueByTypeCode("appellation");
            sourceList = dicValueService.queryDicValueByTypeCode("source");
            transactionList = tranService.selectTransactionListByContactsId(id);
            stageList = dicValueService.queryDicValueByTypeCode("stage");
            transactionTypeList = dicValueService.queryDicValueByTypeCode("transactionType");
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }

        request.setAttribute("userList", userList);
        request.setAttribute("stageList", stageList);
        request.setAttribute("transactionTypeList", transactionTypeList);
        request.setAttribute("contacts", contacts);
        request.setAttribute("remarkList", remarkList);
        request.setAttribute("appellationList", appellationList);
        request.setAttribute("sourceList", sourceList);
        request.setAttribute("activityList", activityList);
        request.setAttribute("transactionList", transactionList);
        //请求转发
        return "workbench/contacts/detail";
    }

    @RequestMapping("/workbench/contacts/queryContactsLikeName")
    public @ResponseBody
    Object selectLikeName(String contactsName) {
        List<Contacts> contacts = null;
        try {
            contacts = contactsService.selectLikeName(contactsName);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        return contacts;
    }


}
